from rest_framework import serializers
from asset.models import Host
from .mixins  import *
import json

from django.contrib.auth import get_user_model
Users = get_user_model()


class Hostserializer(serializers.ModelSerializer,AssetMixin):
    """  主机资产序列化 """

    gmt_create = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    gmt_modified = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
 

    def set_validated_data(self,validated_data):

        if "ssh_id" in self.initial_data.keys():
            validated_data['ssh_id'] = self.get_ssh_id()

        if "platform_id" in self.initial_data.keys():
            validated_data['platform_id'] = self.get_platform_id()

        if "region_id" in self.initial_data.keys():
            validated_data['region_id'] = self.get_region_id()
        if "group_id" in self.initial_data.keys():
            validated_data['group_id'] = self.get_group_id()
             
        return validated_data   

    def create(self, validated_data):
        validated_data = self.set_validated_data(validated_data)
        return super().create(validated_data)
    
    def update(self,instance,validated_data):
        validated_data = self.set_validated_data(validated_data)
        return super().update(instance, validated_data)
    

    class Meta:
        model = Host
        fields = "__all__"  # 1. 显示所有字段
        depth = 1           # 正向序列化；深度1-3层展示 展示外键嵌套{}
        # exclude = ('id',) # 2 排除字段显示所有
        #fields = ('id','hostname','instance_id','ssh_id')
        # read_only_field = ()  # 统一设置字段readonly = true 只读不可修改
        # 附加额外关键字参数
        # extra_kwargs = {
        #     'ssh_id': { "id": 1 }
        #     }

    def to_representation(self, instance):
        """自定义字段返回 """
        data = super().to_representation(instance)
        
        data['asset_type_display'] = instance.get_asset_type_display()
        data['asset_status_display'] = instance.get_status_display()
        data['asset_platformName'] = data['platform_id']['name'] if data['platform_id'] else []
        data['asset_regionName']= data['region_id']['region'] if data['region_id'] else []
      
        if  data['ssh_id']:
            data['asset_sshName'] = data['ssh_id']['name']
            data["ssh_id"]['password'] = "******"  if data["ssh_id"]['password'] else []
            data["ssh_id"]['private'] = "******"  if data["ssh_id"]['private'] else []

        for key in data:
            # 将默认值null设为空;排除元组的choices
            if key != "status" and not data[key]:
                data[key] = ""
        return data
  

